import {
  Body,
  Controller,
  Get,
  HttpException,
  HttpStatus,
  Param,
  Post,
} from '@nestjs/common';
import { UserService } from './user.service';
import { User } from 'src/models/user';
import { GetListDto } from 'src/interface';

@Controller(`user`)
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Get('/count')
  async getCount(): Promise<User[] | number> {
    return await this.userService.queryCount();
  }

  @Get(':id')
  async getOneUsers(@Param('id') id: string): Promise<User[] | null> {
    return await this.userService.findOne(id);
  }

  @Post('/getList')
  async getUsers(@Body() getListDto: GetListDto): Promise<User[] | null> {
    return await this.userService.findList(getListDto);
  }

  @Post('/create')
  async createUser(@Body() createDto: User): Promise<User> {
    const userList = await this.userService.findAll();
    if (userList.length) {
      for (let i = 0, length = userList.length; i < length; i += 1) {
        const element = userList[i];
        if (createDto.username === element.username) {
          throw new HttpException(
            { status: 403, message: '您填入的用户名已经存在' },
            HttpStatus.FORBIDDEN,
          );
        } else {
          return await this.userService.createData(createDto);
        }
      }
    } else {
      return await this.userService.createData(createDto);
    }
  }

  @Post('/update/:id')
  async upDataUsers(
    @Param('id') id: string,
    @Body() upDataUserDto: User,
  ): Promise<User[] | null> {
    return await this.userService.updateData(id, upDataUserDto);
  }

  @Post('/remove/:id')
  async removeUser(@Param('id') id: string): Promise<any> {
    return await this.userService.removeData(id);
  }

  @Post('/delete')
  async removeMenus(@Body() deleteMenusDto: string[]): Promise<any> {
    return await this.userService.deleteData(deleteMenusDto);
  }
}
